package cn.edu.hnu.gpg.handler;

import cn.edu.hnu.gpg.api.error.*;
import cn.edu.hnu.gpg.entity.User;
import cn.edu.hnu.gpg.entity.enums.UserType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ApiAuthCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws UnauthenticatedException, NotFoundException, PermissionDeniedException {
        if (request.getSession(false) == null) {
            throw new UnauthenticatedException(new ApiError(ApiError.ErrorType.ERR_LOGIN_REQUIRED));
        } else {
            User user = (User) request.getSession(false).getAttribute("user");
            if (user == null) {
                throw new UnauthenticatedException(new ApiError(ApiError.ErrorType.ERR_LOGIN_REQUIRED));
            }
            String[] parts = request.getRequestURI().split("/");
            if (parts.length < 2) {
                throw new NotFoundException();
            }

            String subsystem = parts[1];
            switch (subsystem) {
                case "admin":
                    if (user.getUserType() == UserType.A)
                        return true;
                    else throw new PermissionDeniedException();
                case "student":
                    if (user.getUserType() == UserType.S)
                        return true;
                    else throw new PermissionDeniedException();
                case "teacher":
                    if (user.getUserType() == UserType.T)
                        return true;
                    else throw new PermissionDeniedException();

                    default:
                        return true;
            }
        }
    }
}
